import { _decorator, BoxCollider2D, CircleCollider2D, Color, Component, director, EventTouch, Input, RigidBody2D, Sprite, tween, PolygonCollider2D, Vec3 } from 'cc';
import { Clips, events } from './Enums';
import { AudioManger } from './AudioManger';
import { ColorDate } from './ColorDate';
import { Global } from './Global';
import { HoleAction } from './HoleAction';

const { ccclass, property } = _decorator;

@ccclass('PinAction')
export class PinAction extends Component {
    pin_color: ColorDate = null;

    @property({ type: Sprite })
    pin_img: Sprite = null!;

    pos_hole: HoleAction = null;

    flying: boolean = false;

    start() {
        this.node.on(Input.EventType.TOUCH_START, this.touch_start, this);
    }

    is_flying(): boolean {
        return this.flying;
    }

    set_flying(f: boolean) {
        this.flying = f;
    }

    init_date(group_id: number, pin_color: ColorDate, hole: HoleAction) {
        this.pos_hole = hole;
        const rigidBody = this.node.getComponent(RigidBody2D);
        if (rigidBody) rigidBody.group = group_id;

        this.node.getComponents(BoxCollider2D).forEach(collider => collider.group = group_id);
        this.node.getComponents(CircleCollider2D).forEach(collider => collider.group = group_id);
        this.node.getComponents(PolygonCollider2D).forEach(collider => collider.group = group_id);

        this.pin_color = pin_color;
        this.reset_img();
    }

    touch_start(e: EventTouch) {
        if (Global.is_check_completed) {
            console.log("---    is_check_completed  ---");
            return;
        }

        AudioManger.instance.playSound(Clips.pin_1);

        if (Global.layer_cat_action.put_pin(this)) {
            director.emit(events.check_guide, this);
            return;
        }

        Global.layer_empty_action.put_pin(this);

        if (Global.layer_empty_action.is_pin_full()) {
            Global.is_check_completed = true;
            tween(this.node).delay(1.4).call(() => {
                if (Global.layer_empty_action.is_pin_full()) {
                    console.log("---game over---");
                    Global.game_over_action.open();
                } else {
                    console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                }
                Global.is_check_completed = false;
            }).start();
        }

        director.emit(events.check_guide, this);
    }

    remove_collider() {
        const rigidBody = this.node.getComponent(RigidBody2D);
        if (rigidBody) rigidBody.enabled = false;

        const circleCollider = this.node.getComponent(CircleCollider2D);
        if (circleCollider) circleCollider.enabled = false;

        this.node.off(Input.EventType.TOUCH_START);
    }

    reset_img() {
        if (!this.pin_color) return;
        this.pin_img.color = new Color(this.pin_color.r, this.pin_color.g, this.pin_color.b, 255);
    }
}
